#!/usr/bin/env python3
# -*- coding: utf-8 -*-
from tkinter import *
import requests
import bs4


# 解析html页面的译文，仅适用于有道翻译页面
def query_translation(html_page):
    # 转化 html 页面
    soup = bs4.BeautifulSoup(html_page, 'html.parser')
    # 遍历所有的div标签
    for div in soup.body.div.find_all('div'):
        # 用来搜寻 class = 'generate' 这个属性
        temp = ''
        try:
            # 查找是否有 class 这个元素，没有找到抛出异常
            temp = div['class'][0]
        except Exception as e:
            # 不做处理，进行下一个判断
            pass
        # 找到目标 div，接着找到目标 li，找到 li 中的 译文
        if "generate" == temp:
            li = div.ul.li
            text = li.text
            return text


def translate():
    # url='http://fanyi.youdao.com/translate_o?smartresult=dict&smartresult=rule'
    # url='http://fanyi.youdao.com/translate?smartresult=dict&smartresult=rule'
    url = 'https://m.youdao.com/translate'
    content = entry1.get().strip()
    print('content', content)
    data = {'inputtext': content,
            'type': 'AUTO'}
    # data={'i':content,'from':'AUTO','to':'AUTO','smartresult':'dict','client':'fanyideskweb',
    #     'salt':'1542892372198','sign':'389ea8d6439613cb8a7343abdac98da3','doctype':'json',
    #     'version':'2.1','keyfrom':'fanyi.web','action':'FY_BY_REALTIME','typoResult':'false'
    # }
    r = requests.post(url, data=data)
    ret = r.content.decode()
    # result=json.loads(ret)
    # res.set(result['translateResult'][0][0]['tgt'])
    # 拿到翻译的结果
    result = query_translation(ret)
    res.set(result)
    pass


# pyinstall translate.py
# 实例对象
master = Tk()
# 设置窗口大小，设置坐标
master.geometry('400x100+450+278')
master.title("翻译软件")
# 在图形界面嵌入标签
Label(master, text='请输入：', font=('楷体', 18), fg='red').grid(row=0, column=0)
# 在图形界面嵌入标签
Label(master, text='结  果：', font=('楷体', 18), fg='blue').grid(row=1, column=0)

entry1 = Entry(master, font=('楷体', 18))
entry1.grid(row=0, column=1)

res = StringVar()
entry2 = Entry(master, font=('楷体', 18), state=DISABLED, textvariable=res)
entry2.grid(row=1, column=1)

Button(master, text='翻译', font=('楷体', 18), width=10, command=translate).grid(row=2, column=0, stick=W)
Button(master, text='退出', font=('楷体', 18), width=10, command=master.quit).grid(row=2, column=1, stick=E)
master.mainloop()  # 让界面展示
